package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.results.ErrorCode;
import com.itheima.controller.results.Result;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.system.exception.BizException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/save")
    public Result<Void> save(@RequestBody User user) {
        System.out.println(user);
        userService.save(user);
        return Result.ofSuccess();
    }

    @PutMapping()
    public Result<Void> update( User user) {
        userService.update(user);
        return Result.ofSuccess();
    }

    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Integer id) {
        userService.delete(id);
        return Result.ofSuccess();
    }

    @GetMapping("/{id}")
    public Result<User> get(@PathVariable Integer id) {
        User user = userService.get(id);
        //模拟出现异常，使用条件控制，便于测试结果
        if (id == 10) {
            throw new BizException(ErrorCode.DB_QUERY_NOT_EXIST, "查询出错啦，请重试！");
        }
        return Result.ofSuccess(user);
    }

    @GetMapping("/{page}/{size}")
    public Result<PageInfo<User>> getAll(@PathVariable Integer page, @PathVariable Integer size) {
        PageInfo<User> all = userService.getAll(page, size);
        return Result.ofSuccess(all);
}

    @PostMapping("/login")
    public Result<User> login(String userName, String password) {
        User user = userService.login(userName, password);
        return Result.ofSuccess(user);
    }

}
